package reci.journal.plugins;

import java.io.*;
import java.util.*;

import reci.journal.utils.ExtUtil;
import reci.journal.utils.Macro;


/*
 * Copyright (C) 2014 ReciGames
 * See notice in reci.journal.Main.java.
 */

/**includes vars and methods for a general plugin*/
public abstract class Plugin
{
	/**newline*/
	protected final String nl="\r\n";
	
	/**load settings from file, fills missing fields with defaults, then saves to file*/
	protected Properties loadSettings(Properties props, String path, String comments)
	{
		//
		// read properties from file
		//
		
		BufferedReader br=null;
		
		try
		{
			br=new BufferedReader(new FileReader(path));
			props.load(br);
		}
		catch(Exception e)
		{}
		finally
		{
			ExtUtil.close(br);
		}
		
		//
		// write to file
		//
		
		BufferedWriter bw=null;
		
		try
		{
			bw=new BufferedWriter(new FileWriter(path));
			props.store(bw,comments);
		}
		catch(Exception e)
		{}
		finally
		{
			ExtUtil.close(bw);
		}
		
		return props;
	}
	
	/**prints key=value for all properties*/
	protected void printSettings(Properties props)
	{
		for(Map.Entry<Object,Object> e : props.entrySet())
		{
			System.out.println(e.getKey()+"="+e.getValue());
		}
	}

	/**generates HTML file based on template and rules*/
	protected String generateHTML(String outputPath, String templatePath, HashMap<String,String> rules)
	{
		Macro.init(rules);
		
		BufferedReader r=null;
		BufferedWriter w=null;
		
		try
		{
			r=new BufferedReader(new FileReader(templatePath));
			w=new BufferedWriter(new FileWriter(outputPath));
			
			String line;
			while((line=r.readLine())!=null)
			{
				String processed=Macro.process(line);
				w.write(processed);
				w.write(nl);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			ExtUtil.close(r);
			ExtUtil.close(w);
		}
		
		return outputPath;
	}
}
